package com.aliyun.oss;



import lombok.Data;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 阿里云 OSS 工具类
 */
@Data
public class AliOSSUtils {
    AliOSSProperties aliOSSProperties;

    /**
     * 实现上传图片到OSS
     */
    public String upload(MultipartFile multipartFile) throws IOException {
        // 获取上传的文件的输入流
        InputStream inputStream = multipartFile.getInputStream();

        // 避免文件覆盖
        // 拿到文件的真实名字和扩展名
        String originalFilename = multipartFile.getOriginalFilename();
        String[] strings = originalFilename.split("\\.");
        // 拼接文件名字
        String fileName = UUID.randomUUID().toString() + "." + strings[strings.length - 1];

        // 上传文件到OSS
        OSS ossClient = new OSSClientBuilder().build(aliOSSProperties.getEndpoint(), aliOSSProperties.getAccessKeyId(), aliOSSProperties.getAccessKeySecret());
        ossClient.putObject(aliOSSProperties.getBucketName(), fileName, inputStream);

        //文件访问路径
        //https://tlias-shstudy.oss-cn-hangzhou.aliyuncs.com/0986ef13-d301-41bc-bc91-9ccaed9f3062.jpg

        String protocol = "https://";
        if (!aliOSSProperties.getEndpoint().startsWith("http://") && !aliOSSProperties.getEndpoint().startsWith("https://")) {
            aliOSSProperties.setEndpoint(protocol + aliOSSProperties.getEndpoint());
        }
        // 构建URL
        String url = protocol + aliOSSProperties.getBucketName() + "." + aliOSSProperties.getEndpoint().substring(protocol.length()) + "/" + fileName;

        // 关闭ossClient
        ossClient.shutdown();
        return url;// 把上传到oss的路径返回
    }
}
